package com.wzdigit.wms.wms.service.basic;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzdigit.wms.basic.domain.basic.UserWorkDivison;
import com.wzdigit.wms.basic.util.HttpSessionUtil;
import com.wzdigit.wms.basic.client.request.basic.SetUserWorkDivisionRequest;
import com.wzdigit.wms.basic.client.response.Result;
import com.wzdigit.wms.basic.client.response.basic.UserWorkDivisionResponse;
import com.wzdigit.wms.basic.mapper.core.basic.UserWorkDivisonMapper;
import com.wzdigit.wms.basic.mapper.core.basic.WorkDivisionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 用户-工作分工
 * @author yangdongjie
 * @DivisionOfLaborService.java
 * @2021年3月11日下午1:57:22
 */
@Service
public class UserWorkDivisionService {
	
	@Autowired
	private WorkDivisionMapper workDivisionMapper;
	
	@Autowired
	private UserWorkDivisonMapper userWorkDivisonMapper;
	
	/**
	 * 查询指定用户工作分工权限
	 * @param userId
	 * @return
	 */
	public List<UserWorkDivisionResponse> getPermByUserId(Integer userId) {
		return workDivisionMapper.selectPermByUserId(userId);
    }
	
	/**
	 * 设置用户工作分工权限
	 * @param dto
	 * @param servletRequest
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public <T> Result<T> setUserWorkDivision(SetUserWorkDivisionRequest dto, HttpServletRequest servletRequest) {
		String loginName = HttpSessionUtil.getLoginName(servletRequest);
		// 删除关联用户的原有权限
		QueryWrapper<UserWorkDivison> userWorkDivisonQueryWrapper = new QueryWrapper<>();
		userWorkDivisonQueryWrapper.in("USER_ID", dto.getUserId());
		userWorkDivisonMapper.delete(userWorkDivisonQueryWrapper);
		
		// 批量新增
		if(dto.getPermIds() != null && dto.getPermIds().size() > 0) {
			userWorkDivisonMapper.insertList(dto.getUserId(), dto.getPermIds(), loginName, new Date());
		}
		return new Result<>();
	}
}
